package com.xzzz.irda.auth.core.filter.impl;

import com.xzzz.irda.auth.core.authorization.AuthContext;
import com.xzzz.irda.auth.core.authorization.Authorization;
import com.xzzz.irda.auth.core.AuthBaseConfiguration;
import com.xzzz.irda.auth.core.constants.AuthConstant;
import com.xzzz.irda.auth.core.filter.AuthBaseFilterConfiguration;
import com.xzzz.irda.auth.core.filter.AuthFilter;
import com.xzzz.irda.auth.core.filter.AuthFilterChain;
import com.xzzz.irda.auth.core.AuthBaseProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * [200]
 * <p>
 * 令牌刷新, 对令牌进行刷新.
 * 不同类型的令牌刷新不同
 * <p>
 * 注入方式:
 * 由 {@link AuthBaseFilterConfiguration} 注入
 *
 * @author wangyf
 * 
 */
@Slf4j
public class TokenExpireResetFilter implements AuthFilter {

    /**
     * 配置文件内容
     */
    @Autowired
    private AuthBaseProperties properties;

    /**
     * 公用基础配置
     */
    @Autowired
    private AuthBaseConfiguration authBaseConfiguration;

    /**
     * 执行过滤器
     *
     * @param request         request
     * @param response        response
     * @param authFilterChain 过滤器链
     * @throws IOException      io
     * @throws ServletException servlet
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, AuthFilterChain authFilterChain) throws IOException, ServletException {
        log.debug("[AUTHORIZ] filter({}}) 令牌续期", getOrder());

        // 1. 上下文获取授权主体
        Authorization authorization = AuthContext.getContext();

        // 2. 如果配置客户端有效 && 客户端允许刷新令牌
        if (authorization != null && authorization.getRequestRefresh()) {
            // 3.1 刷新存储中的授权信息
            authBaseConfiguration.getAuthorizationRepository().refreshAuthorization(authorization);
            // 3.2 刷新有效token的过期时间
            authBaseConfiguration.getAuthorizationRepository().refreshUniqueToken(authorization);
            // 3.3 刷新上下文授权信息
            AuthContext.setContext(authorization);
        } else {
        }

        // 4. 执行下一个过滤器
        authFilterChain.doFilter(request, response);
    }

    @Override
    public int getOrder() {
        return AuthConstant.Filter.TOKEN_EXPIRE_RESET_FILTER;
    }

}
